package com.edward.migration.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.edward.migration.model.MigrationDatabaseInfo;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

public class DbConnect {

    private DbConnect() {

    }


    public static JdbcTemplate getJdbcTemplate(MigrationDatabaseInfo databaseInfo) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(getDatasource(databaseInfo));
        return jdbcTemplate;
    }

    public static JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    public static TransactionTemplate getTransactionTemplate(DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        return new TransactionTemplate(transactionManager);
    }

    public static DataSource getDatasource(MigrationDatabaseInfo databaseInfo){
        DruidDataSource dataSource = new DruidDataSource();
        //设置连接参数
        dataSource.setUrl(databaseInfo.getDriveUrl());
        dataSource.setDriverClassName(databaseInfo.getDriverClassName());
        dataSource.setUsername(databaseInfo.getUsername());
        dataSource.setPassword(databaseInfo.getDataPassword());
        //配置初始化大小、最小、最大
        dataSource.setInitialSize(2);
        dataSource.setMinIdle(2);
        dataSource.setMaxActive(2);
        //连接泄漏监测
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(30);
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(2000000);
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(2000000);
        //防止过期，Oracle必须添加 FROM DUAL!
        dataSource.setValidationQuery("SELECT 'x' FROM DUAL");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(true);
        return dataSource;
    }
}